// pages/index/search.js
const BizService = require('../../services/biz');
const BizGoodsService = require('../../services/bizGoods');
const GoodsService = require('../../services/goods');

Page({
    /**
     * 页面的初始数据
     */
    data: {
        keyword: '', // 搜索关键词
        dataList: [], // 商家列表
        total: 0, // 总数
        page: 1, // 当前页码
        pageSize: 10, // 每页数量
        hasMore: true, // 是否有更多数据
        loading: false, // 是否正在加载
        searched: false, // 是否已经搜索过
        activeTab: 'biz' // 当前激活的标签
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        // 如果有传入关键词，直接搜索
        if (options.keyword) {
            this.setData({
                keyword: options.keyword
            });
            this.onSearch();
        }
    },

    /**
     * 关键词输入事件
     */
    onKeywordInput(e) {
        this.setData({
            keyword: e.detail.value
        });
    },

    /**
     * 清空关键词
     */
    onClearKeyword() {
        this.setData({
            keyword: '',
            dataList: [],
            total: 0,
            page: 1,
            hasMore: true,
            searched: false
        });
    },

    /**
     * 执行搜索
     */
    async onSearch() {
        const { keyword } = this.data;

        if (!keyword.trim()) {
            wx.showToast({
                title: '请输入搜索关键词',
                icon: 'none'
            });
            return;
        }

        this.setData({
            loading: true,
            page: 1,
            dataList: [],
            hasMore: true,
            searched: true
        });

        try {
            let result = null;
            if (this.data.activeTab == 'biz') {
                result = await BizService.searchBiz({
                    keyword: keyword.trim(),
                    page: 1,
                    pageSize: this.data.pageSize,
                    showLoading: false
                });
            }else if(this.data.activeTab == 'biz-goods'){
                result = await BizGoodsService.searchGoods({
                    keyword: keyword.trim(),
                    page: 1,
                    pageSize: this.data.pageSize,
                    showLoading: false
                });
            }else if(this.data.activeTab == 'store-goods'){
                result = await GoodsService.searchGoods({
                    keyword: keyword.trim(),
                    page: 1,
                    limit: this.data.pageSize,
                    showLoading: false
                });
            }

            console.log(result);

            if (result.success) {
                this.setData({
                    dataList: result.data || [],
                    total: result.total,
                    hasMore: (result.data || []).length >= this.data.pageSize,
                    loading: false
                });
            } else {
                wx.showToast({
                    title: result.message || '搜索失败',
                    icon: 'none'
                });
                this.setData({
                    loading: false
                });
            }
        } catch (error) {
            console.log(error);
            wx.showToast({
                title: '搜索失败，请重试',
                icon: 'none'
            });
            this.setData({
                loading: false
            });
        }
    },

    /**
     * 加载更多
     */
    async onLoadMore() {
        if (this.data.loading || !this.data.hasMore) {
            return;
        }

        this.setData({
            loading: true
        });

        try {
            const nextPage = this.data.page + 1;
            let result = null;
            if(this.data.activeTab == 'biz'){
                result = await BizService.searchBiz({
                keyword: this.data.keyword.trim(),
                page: nextPage,
                pageSize: this.data.pageSize,
                showLoading: false
                });
            }else if(this.data.activeTab == 'biz-goods'){
                result = await BizGoodsService.searchGoods({
                    keyword: this.data.keyword.trim(),
                    page: nextPage,
                    pageSize: this.data.pageSize,
                    showLoading: false
                });
            
            }else if(this.data.activeTab == 'store-goods'){
                result = await GoodsService.searchGoods({
                    keyword: this.data.keyword.trim(),
                    page: nextPage,
                    limit: this.data.pageSize,
                    showLoading: false
                });
            }

            if (result.success && result.data) {
                const newList = [...this.data.dataList, ...result.data];
                this.setData({
                    dataList: newList,
                    page: nextPage,
                    hasMore: result.data.length >= this.data.pageSize,
                    loading: false
                });
            } else {
                this.setData({
                    loading: false
                });
                if (!result.success) {
                    wx.showToast({
                        title: result.message || '加载失败',
                        icon: 'none'
                    });
                }
            }
        } catch (error) {
            wx.showToast({
                title: '加载失败，请重试',
                icon: 'none'
            });
            this.setData({
                loading: false
            });
        }
    },

    /**
     * 跳转到商家详情
     */
    toBizDetail(e) {
        const id = e.currentTarget.dataset.id;
        if (id) {
            wx.navigateTo({
                url: `/pages/biz/detail?id=${id}`
            });
        }
    },

    /**
     * 跳转到商品详情
     */
    toGoodsDetail(e) {
        const id = e.currentTarget.dataset.id;
        if (id) {
            wx.navigateTo({
                url: `/pages/biz/goods?id=${id}`
            });
        }
    },

    toStoreGoodsDetail(e) {
        const id = e.currentTarget.dataset.id;
        if (id) {
            wx.navigateTo({
                url: `/store/pages/goods/detail?id=${id}`
            });
        }
    },

    /**
     * 评分变化事件
     */
    onChange(e) {
        // 评分变化处理
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        if (this.data.keyword) {
            this.onSearch().then(() => {
                wx.stopPullDownRefresh();
            });
        } else {
            wx.stopPullDownRefresh();
        }
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        if (this.data.hasMore && !this.data.loading) {
            this.onLoadMore();
        }
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    onTabChange(e) {
        const tab = e.currentTarget.dataset.tab;
        this.setData({
            activeTab: tab
        }, function () {
            this.onSearch();
        });
    }
})